﻿using SoTaySinhVienUIT.Common;
using SoTaySinhVienUIT.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Search;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Split Page t template is documented at http://go.microsoft.com/fwlink/?LinkId=234234

namespace SoTaySinhVienUIT {
    /// <summary>
    /// A page that displays a group title, a list of items within the group, and details for the
    /// currently selected t.
    /// </summary>
    public sealed partial class SplitPage : SoTaySinhVienUIT.Common.LayoutAwarePage {
        public SplitPage() {
            this.InitializeComponent();
        }

        #region Page state management

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) {
            SearchPane.GetForCurrentView().ShowOnKeyboardInput = false;
            btnDetail.Visibility = Visibility.Collapsed;

            if (navigationParameter.GetType() == typeof(Dictionary<String, String>)) {
                var dic = navigationParameter as Dictionary<String, String>;

                if (dic.Keys.Contains("group_id")) {

                    var item_id = dic.Where(t => t.Key.Equals("item_id")).ElementAt(0).Value;
                    var group_id = dic.Where(t => t.Key.Equals("group_id")).ElementAt(0).Value;

                    var group = SampleDataSource.GetGroup(group_id);
                    this.DefaultViewModel["Group"] = group;
                    this.DefaultViewModel["Items"] = group.Items;

                    if (group.Items.Count == 0) {
                        // Hide favorite button
                        favToggle.Visibility = Visibility.Collapsed;
                    }
                    else {
                        favToggle.Visibility = Visibility.Visible;
                    }

                    favToggleGroup.Visibility = Visibility.Collapsed;


                    var selectedItem = SampleDataSource.GetItem(item_id);
                    this.itemsViewSource.View.MoveCurrentTo(selectedItem);

                    this.itemListView.SelectedItem = selectedItem;

                    btnDetail.Visibility = Visibility.Visible;
                }
                else {
                    if (dic.Keys.Contains("topic_id")) {
                        var item_id = dic.Where(t => t.Key.Equals("item_id")).ElementAt(0).Value;
                        var topic_id = dic.Where(t => t.Key.Equals("topic_id")).ElementAt(0).Value;

                        var topic = SampleDataSource.GetItem(topic_id);
                        this.DefaultViewModel["Group"] = topic;
                        this.DefaultViewModel["Items"] = topic.Items;

                        if (topic.Items.Count == 0) {
                            // Hide favorite button
                            favToggle.Visibility = Visibility.Collapsed;
                        }
                        else {
                            favToggle.Visibility = Visibility.Visible;
                        }

                        var selectedItem = topic.Items.Where(t => t.UniqueId.Equals(item_id)).ElementAt(0);
                        this.itemsViewSource.View.MoveCurrentTo(selectedItem);

                        this.itemListView.SelectedItem = selectedItem;
                    }
                }
            }
            else {
                // TODO: Create an appropriate data model for your problem domain to replace the sample data
                var group = SampleDataSource.GetGroup((String)navigationParameter);
                this.DefaultViewModel["Group"] = group;
                this.DefaultViewModel["Items"] = group.Items;

                if (group.Items.Count == 0) {
                    // Hide favorite button
                    favToggle.Visibility = Visibility.Collapsed;
                }
                else {
                    favToggle.Visibility = Visibility.Visible;
                }

                favToggleGroup.Visibility = Visibility.Collapsed;

                if (pageState == null) {
                    this.itemListView.SelectedItem = null;
                    // When this is a new page, select the first t automatically unless logical page
                    // navigation is being used (see the logical page navigation #region below.)
                    if (!this.UsingLogicalPageNavigation() && this.itemsViewSource.View != null) {
                        this.itemsViewSource.View.MoveCurrentToFirst();
                    }
                }
                else {
                    // Restore the previously saved state associated with this page
                    if (pageState.ContainsKey("SelectedItem") && this.itemsViewSource.View != null) {
                        var selectedItem = SampleDataSource.GetItem((String)pageState["SelectedItem"]);
                        this.itemsViewSource.View.MoveCurrentTo(selectedItem);
                    }
                }

                btnDetail.Visibility = Visibility.Visible;
            }

            SettingsPane.GetForCurrentView().CommandsRequested += SplitPagePrivacy_CommandsRequested;

        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState) {
            //if (this.itemsViewSource.View != null) {
            //    var selectedItem = (SampleDataItem)this.itemsViewSource.View.CurrentItem;
            //    if (selectedItem != null) pageState["SelectedItem"] = selectedItem.UniqueId;
            //}
        }

        #endregion

        #region Logical page navigation

        // Visual state management typically reflects the four application view states directly
        // (full screen landscape and portrait plus snapped and filled views.)  The split page is
        // designed so that the snapped and portrait view states each have two distinct sub-states:
        // either the t list or the details are displayed, but not both at the same time.
        //
        // This is all implemented with a single physical page that can represent two logical
        // pages.  The code below achieves this goal without making the user aware of the
        // distinction.

        /// <summary>
        /// Invoked to determine whether the page should act as one logical page or two.
        /// </summary>
        /// <param name="viewState">The view state for which the question is being posed, or null
        /// for the current view state.  This parameter is optional with null as the default
        /// value.</param>
        /// <returns>True when the view state in question is portrait or snapped, false
        /// otherwise.</returns>
        private bool UsingLogicalPageNavigation(ApplicationViewState? viewState = null) {
            if (viewState == null) viewState = ApplicationView.Value;
            return viewState == ApplicationViewState.FullScreenPortrait ||
                viewState == ApplicationViewState.Snapped;
        }

        /// <summary>
        /// Invoked when an t within the list is selected.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is Snapped)
        /// displaying the selected t.</param>
        /// <param name="e">Event data that describes how the selection was changed.</param>
        async void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            // Invalidate the view state when logical page navigation is in effect, as a change
            // in selection may cause a corresponding change in the current logical page.  When
            // an t is selected this has the effect of changing from displaying the t list
            // to showing the selected t's details.  When the selection is cleared this has the
            // opposite effect.
            if (this.UsingLogicalPageNavigation()) this.InvalidateVisualState();

            if (itemListView.SelectedItem != null) {
                var filename = (itemListView.SelectedItem as SampleDataItem).Content;

                if (filename.Substring(filename.Length - 3, 3).Equals("rtf")) {

                    await SampleDataSource.CheckLocalDataStorageRtf(filename);

                    StorageFolder folder = ApplicationData.Current.LocalFolder;
                    folder = await folder.CreateFolderAsync("data", CreationCollisionOption.OpenIfExists);
                    folder = await folder.CreateFolderAsync("rtf", CreationCollisionOption.OpenIfExists);
                    var file = await folder.GetFileAsync(filename);

                    Windows.Storage.Streams.IRandomAccessStream randAccStream =
                    await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    // Load the file into the Document property of the RichEditBox.
                    rtbContent.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);
                }
                else {
                   
                }
            }

        }

        /// <summary>
        /// Invoked when the page's back button is pressed.
        /// </summary>
        /// <param name="sender">The back button instance.</param>
        /// <param name="e">Event data that describes how the back button was clicked.</param>
        protected override void GoBack(object sender, RoutedEventArgs e) {
            if (this.UsingLogicalPageNavigation() && itemListView.SelectedItem != null) {
                // When logical page navigation is in effect and there's a selected t that
                // t's details are currently displayed.  Clearing the selection will return
                // to the t list.  From the user's point of view this is a logical backward
                // navigation.
                this.itemListView.SelectedItem = null;
            }
            else {
                // When logical page navigation is not in effect, or when there is no selected
                // t, use the default back button behavior.
                base.GoBack(sender, e);
            }
        }

        /// <summary>
        /// Invoked to determine the name of the visual state that corresponds to an application
        /// view state.
        /// </summary>
        /// <param name="viewState">The view state for which the question is being posed.</param>
        /// <returns>The name of the desired visual state.  This is the same as the name of the
        /// view state except when there is a selected t in portrait and snapped views where
        /// this additional logical page is represented by adding a suffix of _Detail.</returns>
        protected override string DetermineVisualState(ApplicationViewState viewState) {
            // Update the back button's enabled state when the view state changes
            var logicalPageBack = this.UsingLogicalPageNavigation(viewState) && this.itemListView.SelectedItem != null;
            var physicalPageBack = this.Frame != null && this.Frame.CanGoBack;
            this.DefaultViewModel["CanGoBack"] = logicalPageBack || physicalPageBack;

            // Determine visual states for landscape layouts based not on the view state, but
            // on the width of the window.  This page has one layout that is appropriate for
            // 1366 virtual pixels or wider, and another for narrower displays or when a snapped
            // application reduces the horizontal space available to less than 1366.
            if (viewState == ApplicationViewState.Filled ||
                viewState == ApplicationViewState.FullScreenLandscape) {
                var windowWidth = Window.Current.Bounds.Width;
                if (windowWidth >= 1366) return "FullScreenLandscapeOrWide";
                return "FilledOrNarrow";
            }

            // When in portrait or snapped start with the default visual state name, then add a
            // suffix when viewing details instead of the list
            var defaultStateName = base.DetermineVisualState(viewState);
            return logicalPageBack ? defaultStateName + "_Detail" : defaultStateName;
        }

        #endregion

        private void itemListView_GotFocus(object sender, RoutedEventArgs e) {
            this.itemListView.ScrollIntoView(this.itemListView.SelectedItem);
        }

        private void tbNote_PointerExited_1(object sender, PointerRoutedEventArgs e) {

        }

        private void tbNote_LostFocus_1(object sender, RoutedEventArgs e) {

        }

        private void tbNote_TextChanged(object sender, TextChangedEventArgs e) {
            try {
                (itemListView.SelectedItem as SampleDataItem).Note = tbNote.Text;

                tbNote.Select(tbNote.Text.Length, 0);
            }
            catch (Exception exp) { }
        }

        private void btnDetail_Click(object sender, RoutedEventArgs e) {
            if ((itemListView.SelectedItem as SampleDataItem).Topic == null) { // Is Topic
                var itemId = (itemListView.SelectedItem as SampleDataTopic).UniqueId;
                this.Frame.Navigate(typeof(ItemsPage), itemId);
            }
        }

        private void btnHome_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
            this.Frame.Navigate(typeof(TopicGroupedPage), "AllGroups");
        }

        private void imgContent_Tapped(object sender, TappedRoutedEventArgs e) {
            this.Frame.Navigate(typeof(ImageViewer), this.itemListView.SelectedItem as SampleDataItem);
        }

        void SplitPagePrivacy_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args) {
            SampleDataSource.AddSettingsCommands(args);
        }

    }
}
